import { acceptHMRUpdate, defineStore } from 'pinia'
import { store } from '../index'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'
import { decodeAES, encodeAES } from '@/utils/aesRsa'

export const useSignStore = defineStore('sign', () => {
  const { wsLocal } = useCache()
  // 当前选择登录模板
  const activeLoginTemplate = ref('1')
  // 当前插画类型
  const activeIllustrationsType = ref('work')
  // 获取验证码倒计时缓存
  const getCountdownCache = key => {
    return decodeAES(wsLocal.getItem(key))
  }
  // 设置验证码倒计时缓存
  const setCountdownCache = (key, value) => {
    wsLocal.setItem(key, encodeAES(value))
  }
  // 移除验证码倒计时缓存
  const removeCountdownCache = key => {
    wsLocal.removeItem(key)
  }
  // 获取登录模板缓存
  const getLoginTemplateCache = () => {
    if (wsLocal.getItem(CACHE_KEY.LOGIN_TEMPLATE)) {
      activeLoginTemplate.value = decodeAES(wsLocal.getItem(CACHE_KEY.LOGIN_TEMPLATE)).toString()
    } else {
      activeLoginTemplate.value = '1'
      setLoginTemplateCache()
    }
  }
  // 设置登录模板缓存
  const setLoginTemplateCache = () => {
    wsLocal.setItem(CACHE_KEY.LOGIN_TEMPLATE, encodeAES(activeLoginTemplate.value))
  }
  // 移除登录模板缓存
  const removeLoginTemplateCache = () => {
    wsLocal.removeItem(CACHE_KEY.LOGIN_TEMPLATE)
  }

  // 获取插画类型缓存
  const getIllustrationsTypeCache = () => {
    if (wsLocal.getItem(CACHE_KEY.LOGIN_ILLUSTRATIONS_TYPE)) {
      activeIllustrationsType.value = decodeAES(wsLocal.getItem(CACHE_KEY.LOGIN_ILLUSTRATIONS_TYPE)).toString()
    } else {
      activeIllustrationsType.value = 'work'
      setIllustrationsTypeCache()
    }
  }
  // 设置插画类型缓存
  const setIllustrationsTypeCache = () => {
    wsLocal.setItem(CACHE_KEY.LOGIN_ILLUSTRATIONS_TYPE, encodeAES(activeIllustrationsType.value))
  }
  // 移除插画类型缓存
  const removeIllustrationsTypeCache = () => {
    wsLocal.removeItem(CACHE_KEY.LOGIN_ILLUSTRATIONS_TYPE)
  }

  return {
    activeLoginTemplate,
    activeIllustrationsType,
    getCountdownCache,
    setCountdownCache,
    removeCountdownCache,
    getLoginTemplateCache,
    setLoginTemplateCache,
    removeLoginTemplateCache,
    getIllustrationsTypeCache,
    setIllustrationsTypeCache,
    removeIllustrationsTypeCache
  }
})

if (import.meta.hot) {
  import.meta.hot.accept(acceptHMRUpdate(useSignStore, import.meta.hot))
}

export const useSignStoreWithOut = () => {
  return useSignStore(store)
}
